import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router,ActivatedRoute} from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
declare var $: any;
declare var BMap: any;
declare var toWGS84: any;
declare var toMapPoint: any;
declare var timestampToTime: any;
declare var trackLineToTime: any;
@Component({
	selector: 'sa-site-manage-page',
	templateUrl: './site-manage-page.component.html',
	styleUrls: ['./trajectory.css']
})
export class SiteManagePageComponent implements OnInit {
	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute ) {
		activatedRoute.queryParams.subscribe(queryParams => {
			if(queryParams.nowPage){
				this.railManage.nowPage=queryParams.nowPage;
			}
			if(queryParams.id){
				this.railManage.railId=queryParams.id;
			}
		});
	};
	railManage:any={
			railId:undefined,
			nowPage:1
		};//存储由围栏管理跳转进来的数据
	mp: any; //百度地图
	myTrackLine: any;
	mapSize: any =16;
	railTitle:any ='新建';
	trackCanvasLayer: any; //轨迹图层
	startCanvasLayer: any; //轨迹起始点图层
	moveCanvasLayer: any; //轨迹移动添加点图层
	canvasLayerRunning: any; //轨迹播放时的图层
	broadcastSpeed :number= 80; //初始默认播放速度为80毫秒,监听控制器播放速度
	starType :number= 1; //初始播放类型设为1，点击播放变为-1，点击暂停变为1
	progressLeft: number = 0; //播放点的left值
	lineLongness :number= 500; //读条线总长度
	timer: any; //播放轨迹时的定时器
	playStarTime:number = 0; //轨迹播放器开始时间
	playEndTime: any = 24; //轨迹播放器结束时间
	parameterArr :any= []; //记录绘画轨迹时,后台传过来的数据(过滤转成百度坐标系);
	trajectoryControlData :any= []; //记录补充后台传过来的数据(包括丢失部分的数据)
	lostDataArr :any= []; //存储丢失数据的对象
	filterTime:number = 300; //定义过滤丢失数据的时间长  单位：秒
	lostTimeArr :any= []; //记录丢失数据的数据(时间点,时间长,对应在播放器的长度及位置)  

	//围栏标注模块
	isRailView :boolean= false; //是否显示添加围栏视图

	companyList :any= []; //获取的公司信息
	railCompany :string= ''; //围栏所属公司

	deployTypeList :any= [{
		name:'装货点',
		value:1
	},{
		name:'卸货点',
		value:2
	}];
	deployType :string= '2'; //选中的类型

	railRangeList :any= ['10','20','30','40','50','60','70','80','90','100', '200', '300', '400', '500', '1000', '2000', '3000', '4000', '5000'];
	railRange :any= '500'; //选中的围栏范围

	railName:string = ''; //围栏名称
	stayTime :any= ''; //围栏停留时长
	isRangeView :boolean= true; //是否显示范围,画多边形的时候不显示
	railColor:string = '#A90329'; //选中的围栏颜色
	railGraphlist:any = []; //所有的围栏图形
	graphical: any = false; //当前的围栏图形
	drawingManager: any; //画多边形构造器
	railType :number= 0; //监听画图的类型
	myIcon1: any;
	myIcon2: any;
	editParam: any=false; //修改的参数
	fristPathArr :any= []; //记录第一次画多边形时候的数组
	graphPoint; //监听状态的坐标
	listenMarker; //监听状态的marker
	isEditing: any = false; //图形是否在编辑状态
	tableHeight : any ;
	
	treeStatus:string='收起';//树形图展开或者收起状态
	btnDownTime:number=0;//截留btn点击展开频率
	selectedCompanyName :string= '';//选中公司名称值

	//行政区域参数
	boundaryRegion:any;//行政边界区域构造器
	areaPly:any;//行政边界区域的覆盖图形
	
	weightUnit:string=' 吨';//树形图展开或者收起状态
//树形图部分start 
	carTreeData=[];//车辆树形图数据
	slectedCarId='';//车辆树形图选中的车辆ID
	notOnlineCar=false;
	findCarCount=0;//车辆树搜出的总数
	findCarIndex=0;//车辆树当前定位
	findString='';//搜索提示
	initWeightline=[];//存储从后台过来时的折线数据,不经过过滤

	rangeClick(){
		$('#tree_selectedRange').stop().slideToggle();
	}
	
	//范围树模糊搜索
	rangeSearch(){
		var value = $('#range').val();
		$("#rangeTree").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1){
			return;
		}
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#vision_rangetree'),
				scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#vision_rangetree').height() * 0.3});
			}
		})
	}
	
	delRange(){
		this.railRange='';
		$('#company').val("");
		if($('#tree_selectedRange')[0].className.indexOf('tree_open')>0){
			$('#range').focus();
			this.rangeSearch();
		}
	}
	initSelectedRange(){
		var that = this;
		var railRangeList = [10,20,30,40,50,60,70,80,90,100,200,300,400,500,1000,2000,3000,4000,5000];
		var rangeTree=[];
		for(let i=0;i<railRangeList.length;i++){
			let obj={
				icon: false,
				id: railRangeList[i],
				text:railRangeList[i]+'米',
			}
			rangeTree.push(obj);
		}
	 	$('#rangeTree').jstree({
			"core": {
			'data':rangeTree,
			"themes": {
				"responsive": true
			},
			"multiple": false,
			"animation": 200,
			"dblclick_toggle": true,
			"expand_selected_onload": true
		},
		"plugins": ["search"]
		}).bind("activate_node.jstree", function(e, obj) {
			var currentNode = obj.node; // 获取当前节点   
			that.railRange=currentNode.id;
			that.rangeChange(currentNode.id);
			$('#tree_selectedRange').slideUp();
		})
	}
	
	//打开公司树
	companyClick(){
		$('#tree_selectedRange').slideUp();
		$('#tree_box').toggleClass('tree_open');
	}
	//擦除公司所选值
	delText(){
		this.selectedCompanyName = '';
		this.railCompany = '';
		$('#company').val("");
		if($('#tree_box')[0].className.indexOf('tree_open')>0){
			$('#company').focus();
			this.companySearch();
		}
	}
	//公司树模糊搜索
	companySearch(){
		var value = $('#company').val();
		$("#tree").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1){
			return;
		}
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#vision_tree'),
				scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#vision_tree').height() * 0.3});
			}
		})
	}
	//初始化公司树数据
	initCompanyList(){
		var that = this;
		return new Promise(function (resolve, reject) {
			$('#tree').jstree({
				"core": {
					'data': function(obj, callback) {       
						var jsonstr = "[]";       
						var jsonarray = eval('(' + jsonstr + ')');
						var url = 'company/companytree.html';
						$.ajax({        
							type: "GET",
					        url: config.BaseURL + url,
					        dataType: "json",
							xhrFields: {
								withCredentials: true
							},
					        success: function(result) {
								jsonarray = result;  
								callback.call(this, jsonarray);
								that.companyList = jsonarray;
							}         
						});       
					},
				"themes": {
					"responsive": true
				},
				"multiple": false,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"plugins": ["search"]
			}).bind("activate_node.jstree", function(e, obj) {
				var currentNode = obj.node; // 获取当前节点   
				that.selectedCompanyName = currentNode.text;
				that.railCompany = currentNode.id;
			})
			resolve();
		}.bind(this))
	}
	

	//初始化绘图围栏的各项参数
	initRailParam() {
		this.isEditing = false; //不在编辑删除状态中
		this.graphical = false; //当前的围栏图形
		this.graphPoint = false;
		this.selectedCompanyName='';
		this.railName = ''; //围栏名称
		this.stayTime = ''; //围栏停留时长
		this.railCompany = ''; //围栏所属公司
		this.deployType = '2'; //选中的类型
		this.railRange = '500'; //选中的围栏范围
		this.isRangeView = true; //是否显示范围,画多边形的时候不显示
		this.railColor = '#A90329'; //选中的围栏颜色
		this.railType = 0; //监听画图的类型
		this.listenMarker = false;
		this.initDrawingStyle();//初始化多边形绘画构造器
		$('.myColor').removeClass('myColor').text('');
		$('.slectColor li').eq(0).addClass('myColor').text('✓ ');
	}
	//颜色选择
	selectedRailCorlor() {
		let that = this;
		$('.slectColor li').click(function() {
			//选择颜色事件
			$('.myColor').text(' ').removeClass('myColor');
			$(this).addClass('myColor').text('✓ ');

			that.railColor = $(this).attr('style').split(':')[1];
			that.initDrawingStyle();//初始化多边形绘画构造器
			if(that.isEditing) {
				var len = that.railGraphlist.length;
				for(var i = 0; i < len; i++) {
					if(that.editParam.point == that.railGraphlist[i].point) {
						that.mp.removeOverlay(that.railGraphlist[i].graphical);
						that.graphical = that.createGraphical(that.railGraphlist[i], that.railColor);
						that.railGraphlist[i].graphical = that.graphical;
						that.mp.addOverlay(that.graphical);
						if(that.railGraphlist[i].lnglats&&that.railGraphlist[i].lnglats!==''){
							//判断为多边形的时候可以进行编辑
							that.graphical.enableEditing();
						}
						
					}
				}
			} else {
				that.mp.removeOverlay(that.graphical);
				if(that.railType == 1) {

					that.graphical = new BMap.Circle(that.graphPoint, that.railRange, {
						strokeColor:'blue',
						fillColor:'red',
						strokeWeight:1,
						strokeOpacity:0.2,
						fillOpacity:0.2
					}); //创建圆

				}
				if(that.railType == 2) {

					that.graphical = new BMap.Polygon(that.fristPathArr, {
						strokeColor:'blue',
						fillColor:'red',
						strokeWeight:1,
						strokeOpacity:0.2,
						fillOpacity:0.2
					}); //创建多边形

				}
				that.mp.addOverlay(that.graphical);
			}
		})
	}
	//编辑或者添加围栏的保存事件
	saveDeploy(isSaveAndCreate) {
		var param = {
			id: '',
			railName: '',
			companyId: '',
			companyName:this.selectedCompanyName,
			typeId: '',
			typeName: '',
			railType: 0,
			radius: '',
			color: '',
			lnglats: '',
			lng: '',
			lat: '',
			stayTime: '',
		};
		if(!this.isEditing) {
			if(!this.graphical) {
				this.jsonApiService.message('请添加围栏标注区域')
				return;
			}
		} else {
			param.id = this.editParam.id;
		}
		param.railName = this.railName;
		param.companyId = this.railCompany
		if(param.railName == '') {
			this.jsonApiService.message('名称不能为空');
			return;
		}
		if(param.companyId == '') {
			this.jsonApiService.message('请选择所属公司...');
			return;
		}
		if(!this.deployType) {
			this.jsonApiService.message('请选择类型...');
			return;
		}
		if(!this.stayTime) {
			this.jsonApiService.message('请填写围栏停留时长');
			return;
		}

		if (!(/(^[1-9]\d*$)/.test(this.stayTime))) { 
			this.jsonApiService.message('请填写正确的围栏停留时长');
			return;
　　　　}
		param.typeId = this.deployType;
		param.typeName = $('.deployType:selected').text();
		param.railType = this.railType;
		param.stayTime = this.stayTime;
		var wgsPoint=toWGS84({lng:this.graphPoint.lng,lat:this.graphPoint.lat});
		param.lng = wgsPoint.lng;
		param.lat = wgsPoint.lat;
		var path =this.graphical.getPath();
		var pointStr = '';
		for(var i = 0; i < path.length; i++) {
			var _point=toWGS84({lng:path[i].lng,lat:path[i].lat});
			pointStr = pointStr + _point.lng + ',' + _point.lat + ';'
		}
		param.lnglats = pointStr;
		if(this.railType == 1) {
			param.lnglats = '';
		}
		if(this.isEditing) {
			//判断是否编辑状态
			if(this.editParam.lnglats == '') {
				param.lnglats = '';
			}
		}
		
		if(param.lnglats=='') {
			if(!this.railRange){
				this.jsonApiService.message('请输入正确的围栏范围...');
				return;
			}
			param.radius = this.railRange+'';
		} else {
			param.radius = '0';
		} 
		param.color = this.railColor;
		this.mp.closeInfoWindow();
		let reqdata = '';
		for(var item in param) {
			reqdata = reqdata + '&' + item + '=' + param[item];
		}
		var url = "environmentalRail/addEnvironmentalRail.html";
		if(param.id){
			url = "environmentalRail/editEnvironmentalRail.html"
		}
		this.jsonApiService.http(url, reqdata).subscribe(result => {
			this.graphical.disableEditing();
			if(!result.success) {
				this.jsonApiService.message(result.message);
				return;
			}
			if(this.isEditing&&param.lnglats == ''){
				this.mp.removeOverlay(this.railGraphlist[this.isEditing - 1].graphical);
				this.clearAllGraph();
				// this.initAllRailGraph();
				this.editParam=false;//清空之前可能存在编辑的数据
			}
			var tipsType;
			var backData = result.data;
			backData.point = this.graphPoint;
			backData.marker = this.listenMarker;
			backData.graphical = this.graphical;
			if(this.isEditing || this.isEditing > 0) {
				tipsType = '编辑成功'
				this.railGraphlist[this.isEditing - 1] = backData;
				this.router.navigate(['/environment-manage/site-manage'],{queryParams: {nowPage:this.railManage.nowPage}});
			} else {
				tipsType = '提交成功'
				this.railGraphlist.push(backData);
				this.router.navigate(['/environment-manage/site-manage'],{queryParams: {nowPage:this.railManage.nowPage}});
			}
			this.jsonApiService.message(tipsType);
			var content = this.createContent(backData);
			this.addClickHandler(content, this.listenMarker, backData);
			this.initRailParam();
			this.closeDeploy();
			
			if(isSaveAndCreate) {
				if(backData.radius < 1) {
					this.listenerRail(2);
				} else {
					this.listenerRail(1);
				}
			}
		})
	}
	//取消添加围栏
	cencelDeploy() {
		if(!this.isEditing) {
			this.mp.removeOverlay(this.graphical);
			this.mp.removeOverlay(this.listenMarker);
		}
		this.initRailParam();
		this.closeDeploy();
	}
	//关闭添加围栏操作模块
	closeDeploy() {
		this.isRailView = false;
		$('.selectRail').removeClass('selectRail');
		var len = this.railGraphlist.length;
		for(var i = 0; i < len; i++) {
			this.railGraphlist[i].graphical.disableEditing();
		}
	}
	
	//编辑加载某一个
	initRailGraph() {
//		判断是否由围栏管理编辑进来进行围栏编辑的
		var railId=this.railManage.railId;
		var reqdata = "id=" + this.railManage.railId;
		this.jsonApiService.http2('environmentalRail/getEnvironmentalRail.html',reqdata).subscribe(result => {
			let len = result.data.length;
			var obj = toMapPoint(result.data);
			var point = new BMap.Point(obj.lng, obj.lat);
			var marker = new BMap.Marker(point, {
				icon: this.myIcon2
			});
			if(obj.lnglats == '') {
				marker = new BMap.Marker(point, {
					icon: this.myIcon1
				});
			}
			var myGraph = this.wgsGraphical(obj, false);
			this.mp.addOverlay(marker);
			var infoPoint = point; //因点击保存后要初始化一次，所有存储新的坐标位置
			obj.point = point;
			obj.marker = marker;
			obj.graphical = myGraph;
			this.railGraphlist.push(obj);
			if(railId&&railId===obj.id){
				this.editParam = obj;
			}
			var content = this.createContent(obj);
			this.addClickHandler(content, marker, obj);
			this.mp.addOverlay(myGraph);
			if(this.editParam&&railId){
				this.railManage.railId=undefined;
				this.eidtGraphical();
				this.mp.centerAndZoom(this.editParam.point, this.mapSize); 
			}
		})
	}
	//初始化加载所有围栏覆盖物
	initAllRailGraph() {
//		判断是否由围栏管理编辑进来进行围栏编辑的
		var railId=this.railManage.railId;
		this.jsonApiService.http2('mapmarker/getmarker.html', '').subscribe(result => {
			let len = result.data.length;
			if(len < 1) {
//				this.jsonApiService.message('没有围栏图形数据');
				return;
			}
			for(var i = 0; i < len; i++) {
				var obj = toMapPoint(result.data[i]);
				var point = new BMap.Point(obj.lng, obj.lat);
				var marker = new BMap.Marker(point, {
					icon: this.myIcon2
				});
				if(obj.lnglats == '') {
					marker = new BMap.Marker(point, {
						icon: this.myIcon1
					});
				}
				var myGraph = this.wgsGraphical(obj, false);
				this.mp.addOverlay(marker);
				var infoPoint = point; //因点击保存后要初始化一次，所有存储新的坐标位置
				obj.point = point;
				obj.marker = marker;
				obj.graphical = myGraph;
				this.railGraphlist.push(obj);
				if(railId&&railId===obj.id){
					this.editParam = obj;
				}
				var content = this.createContent(obj);
				this.addClickHandler(content, marker, obj);
				this.mp.addOverlay(myGraph);
			}
			if(this.editParam&&railId){
				this.railManage.railId=undefined;
				this.eidtGraphical();
				this.mp.centerAndZoom(this.editParam.point, this.mapSize); 
			}
		})
	}
	//监听marker点击事件
	addClickHandler(content, marker, obj) {
		let that = this;
		marker.addEventListener("click", function(e) {
			that.editParam = obj;
			var infoWindow = new BMap.InfoWindow(content, {
				width: 200,
			}); 
			that.mp.openInfoWindow(infoWindow, e.point); //开启信息窗口
			$('.BMap_bottom').append('<div class="pointer"></div>');
			$('.eidtRail').on('click', function() {
				that.eidtGraphical();
			});
			$('.delRail').on('click', function() {
				that.delGraphical()
			});
		})
	};
	//创建信息info窗口
	createContent(param) {
		if(param.typeId == '' || !param.typeId) {
			param.typeId = '无';
		}
		if(param.typeId ==='1'){
			param.typeName = '装货点'
		}else if(param.typeId ==='2'){
			param.typeName = '卸货点'
		}

		var content = '<div class="mInfoul"><ul>' +
			'<li>标注名称：' + param.railName + '<li>' +
			'<li>所属公司：' +  param.companyName + '<li>' +
			'<li>所属角色：' + param.createUser + '<li>' +
			'<li>类型：' + param.typeName + '<li>' +
			'<li style="color:#3BA4F9"><span style="float:right;cursor:pointer" class="eidtRail">编辑</span><span style="cursor:pointer" class="delRail">删除</span><li>' +
			'</ul></div>';
		return content;
	}

	//通过公司id获取公司名
	getCompanyName(id) {
		var companyName = '';
		var len = this.companyList.length;
		for(var i = 0; i < len; i++) {
			if(this.companyList[i].id == id) {
				companyName = this.companyList[i].text;
			}
		}
		return companyName;
	}
	//删除围栏图形
	delGraphical() {
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
			var point = this.editParam.point;
			var len = this.railGraphlist.length;
			var reqdata = "id=" + this.editParam.id;
			this.jsonApiService.http('environmentalRail/deleteEnvironmentalRail.html', reqdata).subscribe(result => {
				this.jsonApiService.message(result.message);
			})
			for(var i = 0; i < len; i++) {
				if(this.editParam.point == this.railGraphlist[i].point) {
					this.mp.removeOverlay(this.railGraphlist[i].graphical);
					this.mp.removeOverlay(this.railGraphlist[i].marker);
				}
			}
			this.mp.closeInfoWindow();
			this.initRailParam();

			this.router.navigate(['/environment-manage/site-manage'],{queryParams: {nowPage:this.railManage.nowPage}});
		})
	}

	//修改图形
	eidtGraphical() {
		if(!this.isEditing) {
			this.mp.removeOverlay(this.listenMarker);
			this.mp.removeOverlay(this.graphical);
		}
		if(this.graphical) {
			this.graphical.disableEditing();
		}
		this.initRailParam();
		this.mp.closeInfoWindow();
		this.isRailView = true;
		this.railName = this.editParam.railName;
		this.stayTime = this.editParam.stayTime;
		this.railCompany = this.editParam.companyId;
		this.selectedCompanyName = this.editParam.companyName; 
		this.deployType = this.editParam.typeId;
		this.railRange = this.editParam.radius;
		this.railColor = this.editParam.color;
		this.railType = this.editParam.railType;
		let that = this;
		$('.slectColor li').each(function() {
			var color = $(this).attr('style').split(':')[1];
			if(that.editParam.color == color) {
				$('.myColor').text(' ').removeClass('myColor');
				$(this).addClass('myColor').text('✓ ');
			}
		})
		var point = this.editParam.point;
		var len = this.railGraphlist.length;
		for(var i = 0; i < len; i++) {
			if(this.editParam.point == this.railGraphlist[i].point) {
				this.graphical = this.railGraphlist[i].graphical;
				this.listenMarker = this.railGraphlist[i].marker;
				this.graphPoint = this.railGraphlist[i].point;
				this.isEditing = i + 1;
				if(this.railGraphlist[i].lnglats == '') {
					this.isRangeView = true;
				} else {
					this.isRangeView = false;
					this.graphical.enableEditing();
				}
				break;
			}
		}
	}
	
	
	//大地坐标系转成百度坐标系后绘图
	wgsGraphical(obj, color) {
		var myGraph;
		if(color) {
			obj.color = color;
		}
		if(obj.lnglats == ''||obj.lnglats == null) {
			
			var point = new BMap.Point(obj.lng, obj.lat);
			myGraph = new BMap.Circle(point, obj.radius, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建圆

		} else {
			
			if(!obj.lnglats){
				return;
			}
			var poitnArr = [];
			var lnglatsArr = obj.lnglats.split(';');
			for(var j = 0; j < lnglatsArr.length; j++) {
				if(lnglatsArr[j] !== "") {
					var arr = lnglatsArr[j].split(',');
					var point=toMapPoint({lng:arr[0], lat:arr[1]});
					poitnArr.push(new BMap.Point(point.lng,point.lat))
				}
			}
			myGraph = new BMap.Polygon(poitnArr, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建多边形
		}
		return myGraph;
	}
	
	//根据图形类型创建图形
	createGraphical(obj, color) {
		var myGraph;
		if(color) {
			obj.color = color;
		}
		if(obj.lnglats == ''||obj.lnglats == null) {
			
			var point = new BMap.Point(obj.lng, obj.lat);
			myGraph = new BMap.Circle(point, obj.radius, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建圆

		} else {
			
			if(!obj.lnglats){
				return;
			}
			var poitnArr = [];
			var lnglatsArr = obj.lnglats.split(';');
			for(var j = 0; j < lnglatsArr.length; j++) {
				if(lnglatsArr[j] !== "") {
					var arr = lnglatsArr[j].split(',');
					poitnArr.push(new BMap.Point(arr[0], arr[1]))
				}
			}
			myGraph = new BMap.Polygon(poitnArr, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建多边形
		}
		return myGraph;
	}
	//初始化多边形绘画构造器
	initDrawingStyle() {
		let styleOptions = {
			strokeColor: this.railColor, //边线颜色。
			fillColor: this.railColor, //填充颜色。当参数为空时，圆形将没有填充效果。
			strokeWeight: 3, //边线的宽度，以像素为单位。
			strokeOpacity: 0.8, //边线透明度，取值范围0 - 1。
			fillOpacity: 0.3, //填充的透明度，取值范围0 - 1。
			strokeStyle: 'solid' //边线的样式，solid或dashed。
		}
		let that = this;
		let drawingManager = new BMapLib.DrawingManager(that.mp, {
			isOpen: false, //是否开启绘制模式
			enableDrawingTool: false, //是否显示工具栏
			drawingToolOptions: {
				offset: new BMap.Size(5, 5), //偏离值
				scale: 0.8,
				drawingModes: [
					'polygon', //多边形
				]
			},
			polygonOptions: styleOptions, //多边形的样式
		});
		this.drawingManager = drawingManager;
		drawingManager.addEventListener("overlaycomplete", function(e) {//围栏点击回调事件
			that.graphical = e.overlay;
			var path = that.graphical.getPath();
			that.fristPathArr = path;
			var last = path.length - 1;
			that.graphPoint = that.getCenterPoint(path);
			that.listenMarker = new BMap.Marker(that.graphPoint, {
				icon: that.myIcon2
			}); //棋子图标
			that.mp.addOverlay(that.listenMarker);
			drawingManager.close();
			that.isRailView = true;
		});
	}
	//	获取中心点
	getCenterPoint(path) {

		var x = 0.0;
		var y = 0.0;
		for(var i = 0; i < path.length; i++) {
			x = x + parseFloat(path[i].lng);
			y = y + parseFloat(path[i].lat);
		}
		x = x / path.length;
		y = y / path.length;
		return new BMap.Point(x, y);
	}
	listenerRail(type) {
		//监听点击圆形或多边形按钮事件
		this.selectedCompanyName = '';
		if(this.graphical) {
			this.jsonApiService.message('请先保存图形');
			return;
		}
		if(type == 1) {
			this.railType = 1;
			this.isRangeView = true;
			
			$('.selectRail').removeClass('selectRail');
			$('.rail1').addClass('selectRail');
			this.drawingManager.close();
		}
		if(type == 2) {
			this.railType = 2;
			this.isRangeView = false;
			$('.selectRail').removeClass('selectRail');
			$('.rail2').addClass('selectRail');
			this.drawingManager.open();
			this.drawingManager.setDrawingMode('polygon');
		}
	}
	//清除所有的图形
	clearAllGraph() {
		var len = this.railGraphlist.length;
		for(var i = 0; i < len; i++) {
			this.mp.removeOverlay(this.railGraphlist[i].graphical);
			this.mp.removeOverlay(this.railGraphlist[i].marker);
		}
	}

	//当图形为圆形时范围变更事件
	rangeChange(value) {
		if(!this.graphical) {
			return;
		}
		this.railRange = value;
		if(this.isEditing > 0) {
			if(this.railGraphlist[this.isEditing - 1].lnglats == '') {
				this.mp.removeOverlay(this.railGraphlist[this.isEditing - 1].graphical);
				this.railGraphlist[this.isEditing - 1].radius = parseInt(value);
				this.railGraphlist[this.isEditing - 1].graphical = this.createGraphical(this.railGraphlist[this.isEditing - 1], false);
				this.mp.addOverlay(this.railGraphlist[this.isEditing - 1].graphical);
			}
		}

		if(this.railType == 1) {
			this.mp.removeOverlay(this.graphical);
			this.graphical = new BMap.Circle(this.graphPoint, value, {
				strokeColor:'blue',
				fillColor:'red',
				strokeWeight:1,
				strokeOpacity:0.2,
				fillOpacity:0.2
			}); //创建圆
			this.mp.addOverlay(this.graphical);
		}

	}
	
	ngOnInit() {
		if(this.railManage.railId){
			this.railTitle = "编辑"
		}
		let map = new BMap.Map('baiduMap',{enableMapClick:false}); //创建地图实例
		map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
		var point = new BMap.Point(116.404, 39.915);
        map.centerAndZoom(point, 12);
		//初始化一个行政边界区域构造器
		this.boundaryRegion = new BMap.Boundary();
		this.mp = map;
		let that = this;
		map.addEventListener("zoomend", function(){
			that.mapSize = this.getZoom();
			if(that.isEditing){
				return;
			}
		});
		this.mp.addEventListener("click", function(e){
			//地图点击添加圆形
			if(that.graphical) {
				return;
			}
			if(that.railType == 1) {
				var point = new BMap.Point(e.point.lng, e.point.lat);
				that.graphPoint = point;
				that.listenMarker = new BMap.Marker(point, {
					icon: that.myIcon1
				});
				that.graphical = new BMap.Circle(that.graphPoint, that.railRange, {
					strokeColor:'blue',
					fillColor:'red',
					strokeWeight:1,
					strokeOpacity:0.2,
					fillOpacity:0.2
				}); //创建圆
				that.mp.addOverlay(that.listenMarker);
				that.mp.addOverlay(that.graphical);
				that.isRailView = true;
			}
		});
		this.mp.addEventListener('dblclick', function(e) {
			map.closeInfoWindow(); //关闭信息窗口
		});
		System.import('assets/js/jstree/jstree.min.js').then(()=>{
			this.initSelectedRange();
			this.initCompanyList().then(()=>{
				if(this.railManage.railId){
					this.initRailGraph();
				}
				// this.initAllRailGraph();
			});//初始化公司树
			var tree_box = document.getElementById('tree_box');
			var company = document.getElementById('company');
			var rangeBox=document.getElementById('range');
			//公司树弹窗显示隐藏交互事件
			document.onclick=function(e:any){
				if(!(e.target === company||e.target === rangeBox||e.target.className === 'jstree-children'||e.target.className === 's_del_icon'||e.target.className === 'jstree-node  jstree-leaf'||e.target.className === 'jstree-icon jstree-ocl'||e.target.className ==='vision_tree'||e.target.className === 'jstree-node jstree-leaf jstree-closed')){ 
			        tree_box.className = tree_box.className.replace("tree_open","");
			        $('#tree_selectedRange').slideUp();
			   	} 
			}
		});
		//导入插件插件js
		this.initDrawingStyle();//初始化多边形绘画构造器
		this.initSearch();//区域搜索
		this.selectedRailCorlor();//颜色选择
		this.myIcon1 = new BMap.Icon("assets/img/deployIcon/icon3.png", new BMap.Size(30, 30), {
			imageOffset: new BMap.Size(10, 0)
		}); //圆形的marker图标
		this.myIcon2 = new BMap.Icon("assets/img/deployIcon/icon4.png", new BMap.Size(30, 30), {
			imageOffset: new BMap.Size(10, 0)
		}); //多边形的marker图标
		this.initTextInfo(); //初始化一个info框
		this.addEventWindowResize();
	}
	addEventWindowResize(){
		$(window).on('resize',function(){
			var wrapWidth = $("#wrap").width();
			var divTreeWidth=$(".divTree").width();
			$('.treeRight').width(wrapWidth - divTreeWidth -12 + 'px');
		})
	}
	draggingEvent(){
		var clickX;
		var warp=$("#wrap");
		var treeElement=$(".divTree");
		var treeRight=$(".treeRight");
		var min = 300;
		var max=0;
		var leftOffset = warp.offset().left;
		$(document).on('mousemove', function(e) {
			var wrapWidth = warp.width();
			max=wrapWidth/2;
			var divTreeWidth=treeElement.width();
			var treeRightWidth=treeRight.width();
			clickX = e.pageX;
			//clickX-leftOffset > min   鼠标往右移动,并且大于最小宽度300
			if(clickX-leftOffset > min) {
				if(clickX -leftOffset < max) {
					treeElement.width(clickX - leftOffset + 'px');
					treeRight.width(wrapWidth - clickX + leftOffset -12 + 'px');
				}
				else{
					treeElement.width( max + 'px');
					treeRight.width(wrapWidth - max -12 + 'px');
				}
			} else {
				treeElement.width(min + 'px');
				treeRight.width(wrapWidth - min-12 + 'px');
			}
		});
		
		$(document).mouseup(function(e) {
			e.cancelBubble = true;
			$(document).unbind('mousemove')
		})
	}
	ngOnDestroy() {
		$(document).unbind('keyup'); //移除键盘回车事件
		$(window).unbind('resize');
  	}
	//初始化创建一个info信息窗口
	initTextInfo(){
		let content = '<div><ul>' +
			'<li>标注名称：<li>' +
			'<li>所属公司：<li>' +
			'<li>类型：<li>' +
			'<li style="color:#3BA4F9"><span style="float:right;" class="eidtRail">初始化</span><span class="delRail">删除</span><li>' +
			'</ul></div>';
		var infoWindow = new BMap.InfoWindow(new BMap.Point(0, 0),{
			width: 200,
			heigth: 300
		}); // 创建信息窗口对象 
	}
	
	//初始化地图视图,擦除覆盖物
	initMap() {
		this.mp.removeOverlay(this.trackCanvasLayer);
		this.mp.removeOverlay(this.moveCanvasLayer);
		this.mp.removeOverlay(this.startCanvasLayer);
		this.mp.removeOverlay(this.canvasLayerRunning);
		this.mp.clearOverlays();
		this.parameterArr = [];
		this.trajectoryControlData = [];
		this.lostTimeArr = [];
		this.lostDataArr = [];
		this.starType = 1;
		this.progressLeft = 0;
		clearInterval(this.timer);
		// this.initAllRailGraph();
	}

	//	计算两个经纬度之间的距离
	caculationDistance(point1, point2) {
		var lng1 = point1.lng;
		var lat1 = point1.lat;
		var lat2 = point2.lat;
		var lng2 = point2.lng;
		var earthRadius = 6371393; //地球半径(米)
		var radLat1 = lat1 * Math.PI / 180.0;
		var radLat2 = lat2 * Math.PI / 180.0;
		var a = radLat1 - radLat2;
		var b = (lng1 - lng2) * Math.PI / 180.0;
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * earthRadius;
		return s;
	}

	//区域搜索
	initSearch(){
		let mp=this.mp;
		var that=this;
		let ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{"input" : "suggestId"
			,"location" : mp
		});
		ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
			let str = "";
			let _value = e.fromitem.value;
			let value = "";
			if (e.fromitem.index > -1) {
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
			value = "";
			if (e.toitem.index > -1) {
				_value = e.toitem.value;
				value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
			}    
			str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
			$("#searchResultPanel").text(str);
			let myValue;
			ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件和点击 
				let _value = e.item.value;
				myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
				$("#searchResultPanel").text("onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue);
				setPlace();
			});
			$('#search').click(function(){
				myValue=$('#suggestId').val();
		    	if(myValue!==''){
		    		setPlace();
		    	}
			});
			let setPlace=function (){
				let myFun=function (){
					let pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
					mp.centerAndZoom(pp, 18);
				}
			let local = new BMap.LocalSearch(mp, { //智能搜索
			  onSearchComplete: myFun
			});
			local.search(myValue);
			
			that.drawBoundary(myValue);
		}
		});
	}
	
	//绘画行政区域边界
	drawBoundary(locations){
    	var that=this;
	    this.boundaryRegion.get(locations, function(rs){       //获取行政区域
	    	that.mp.removeOverlay(that.areaPly);  //清除掉之前的边界区域
	        var count = rs.boundaries.length; //行政区域的点有多少个
	      
	      	if(count<1){
	      		
	        	return;
	        }
	        that.areaPly = new BMap.Polygon(rs.boundaries[0], {
	        	strokeColor:'blue',
						fillColor:'red',
						strokeWeight:1,
						strokeOpacity:0.2,
						fillOpacity:0.2
					}); //建立多边形覆盖物
	        that.mp.addOverlay(that.areaPly);  //添加覆盖物
	        that.mp.setViewport(that.areaPly.getPath());    //调整视野  

	        
		})
	}
	// 返回围栏管理
	goBackTo(){
	    this.router.navigate(['/environment-manage/site-manage']);
	}
	
	
}